﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Moqikaka.Util
{
    /// <summary>
    /// 安全哈希表
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="V"></typeparam>
    public class SafeDictionary<K, V> : Dictionary<K, V>
    {
        /// <summary>
        /// Monitor  object
        /// </summary>
        public object obj = new object();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">key</param>
        /// <returns></returns>
        public new V this[K key]
        {
            get
            {
                return this.Get(key);
            }
            set
            {
                this.Set(key, value);
            }
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public V Get(K key)
        {
            V value = default(V);

            try
            {
                Monitor.Enter(obj);
                value = base[key];
            }
            catch (Exception)
            {

            }
            finally
            {

                Monitor.Exit(obj);
            }

            return value;
        }

        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cahe"></param>
        public void Set(K key, V cahe)
        {
            try
            {
                Monitor.Enter(obj);

                base[key] = cahe;
            }
            catch (Exception)
            {

            }
            finally
            {

                Monitor.Exit(obj);
            }
        }

    }
}
